package cn.fresh.xuanyuan.module.system.util.wx;

import cn.fresh.xuanyuan.module.system.model.request.SubscribeMessageRequest;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WXMessageUtil {

    private final static Logger log = LoggerFactory.getLogger(WXMessageUtil.class);

    private final static String WX_MESSAGE_API = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";

    private static final ObjectMapper mapper = new ObjectMapper();

    public static String sendMessage(SubscribeMessageRequest request, String accessToken) {
        String result = null;
        try {
            String url = WX_MESSAGE_API + accessToken;
            String body = toJson(request);
            result = HttpUtil.post(url, body);
            log.info("sendMessage result: {}", result);
        } catch (JsonProcessingException e) {
            log.error("sendMessage exception:", e);
        }
        return result;
    }

    public static String toJson(Object obj) throws JsonProcessingException {
        return mapper.writeValueAsString(obj);
    }
}
